package com.cyz.controller;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cyz.annotation.AuthCheck;
import com.cyz.api.aliyunai.AliYunAiApi;
import com.cyz.api.aliyunai.model.CreateOutPaintingTaskResponse;
import com.cyz.api.aliyunai.model.GetOutPaintingTaskResponse;
import com.cyz.api.imagesearch.ImageSearchApiFacade;
import com.cyz.api.imagesearch.model.ImageSearchResult;
import com.cyz.common.BaseResponse;
import com.cyz.common.DeleteRequest;
import com.cyz.common.ResultUtils;
import com.cyz.constant.UserConstant;
import com.cyz.exception.BusinessException;
import com.cyz.exception.ErrorCode;
import com.cyz.exception.ThrowUtils;
import com.cyz.manager.auth.SpaceUserAuthManager;
import com.cyz.manager.auth.StpKit;
import com.cyz.manager.auth.annotation.SaSpaceCheckPermission;
import com.cyz.manager.auth.model.SpaceUserPermissionConstant;
import com.cyz.model.dto.picture.*;
import com.cyz.model.entity.Picture;
import com.cyz.model.entity.Space;
import com.cyz.model.entity.User;

import com.cyz.model.enums.PictureReviewStausEnums;
import com.cyz.model.vo.PictureTagCategory;
import com.cyz.model.vo.PictureVO;
import com.cyz.service.PictureService;
import com.cyz.service.SpaceService;
import com.cyz.service.UserService;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.time.Duration;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
@RequestMapping("/picture")
public class PictureController {

    @Resource
    UserService userService;

    @Resource
    PictureService pictureService;

    @Resource
    StringRedisTemplate stringRedisTemplate;

    @Resource
    private SpaceService spaceService;

    @Resource
    private AliYunAiApi aliYunAiApi;

    @Resource
    private SpaceUserAuthManager spaceUserAuthManager;

    private final Cache<String, String> LOCAL_CACHE = Caffeine.newBuilder()
            .initialCapacity(1024)
            .maximumSize(10_000L)   // 最大10000条
            // 写入五分钟后移除
            .expireAfterWrite(Duration.ofMinutes(5))
            .build();

    /**
     * 上传图片（可重新上传）
     */
    @PostMapping("/upload")
    @SaSpaceCheckPermission(value = SpaceUserPermissionConstant.PICTURE_UPLOAD)
    public BaseResponse<PictureVO> uploadPicture(
            @RequestPart("file") MultipartFile multipartFile,
            PictureUploadRequest pictureUploadRequest,
            HttpServletRequest request) {
        log.info("上传图片，{},{}", pictureUploadRequest, multipartFile.getOriginalFilename());
        User loginUser = userService.getLoginUser(request);
        PictureVO pictureVO = pictureService.uploadPicture(multipartFile, pictureUploadRequest, loginUser);
        return ResultUtils.success(pictureVO);
    }


    /**
     * 通过 URL 上传图片（可重新上传）
     */
    @PostMapping("/upload/url")
    @SaSpaceCheckPermission(value = SpaceUserPermissionConstant.PICTURE_UPLOAD)
    public BaseResponse<PictureVO> uploadPictureByUrl(
            @RequestBody PictureUploadRequest pictureUploadRequest,
            HttpServletRequest request) {
        log.info("通过url上传图片：{}", pictureUploadRequest);
        User loginUser = userService.getLoginUser(request);
        String fileUrl = pictureUploadRequest.getPictureUrl();
        PictureVO pictureVO = pictureService.uploadPicture(fileUrl, pictureUploadRequest, loginUser);
        return ResultUtils.success(pictureVO);
    }

    /**
     * 删除图片
     *          (可以优化，用户删除仅逻辑删除，管理员可删除永久删除)
     */
    @PostMapping("/delete")
    @SaSpaceCheckPermission(value = SpaceUserPermissionConstant.PICTURE_DELETE)
    public BaseResponse<Boolean> deletePicture(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {

        boolean res = pictureService.deletePictureById(deleteRequest.getId(), request);

        return ResultUtils.success(res);
    }

    /**
     * 更新图片
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updatePicture(@RequestBody PictureUpdateRequest pictureUpdateRequest, HttpServletRequest request) {
        if (pictureUpdateRequest == null || pictureUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 将实体类和 DTO 进行转换
        Picture picture = new Picture();
        BeanUtils.copyProperties(pictureUpdateRequest, picture);
        // 注意将 list 转为 string
        picture.setTags(JSONUtil.toJsonStr(pictureUpdateRequest.getTags()));
        // 数据校验
        pictureService.validPicture(picture);
        // 判断是否存在
        long id = pictureUpdateRequest.getId();
        Picture oldPicture = pictureService.getById(id);
        ThrowUtils.throwIf(oldPicture == null, ErrorCode.NOT_FOUND_ERROR);
        // 获取登录用户信息
        User loginUser = userService.getLoginUser(request);
        // 填充审核信息
        pictureService.fillReviewParam(picture, loginUser);
        // 操作数据库
        boolean result = pictureService.updateById(picture);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    /**
     * 根据 id 获取图片（仅管理员可用）
     */
    @GetMapping("/get")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Picture> getPictureById(long id) {
        ThrowUtils.throwIf(id <= 0, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Picture picture = pictureService.getById(id);
        ThrowUtils.throwIf(picture == null, ErrorCode.NOT_FOUND_ERROR);
        // 获取封装类
        return ResultUtils.success(picture);
    }

    /**
     * 根据 id 获取图片（封装类）
     */
    @GetMapping("/get/vo")
    public BaseResponse<PictureVO> getPictureVOById(long id, boolean isShare, HttpServletRequest request) {

        System.out.println("是否是分享=================================>" + isShare);

        ThrowUtils.throwIf(id <= 0, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Picture picture = pictureService.getById(id);
        ThrowUtils.throwIf(picture == null, ErrorCode.NOT_FOUND_ERROR);
        // 校验是否是分享
        if (isShare) {
            // 是用户分享就直接返回图片视图信息
            return ResultUtils.success(pictureService.getPictureVO(picture, request));
        }
        // 校验图片查询权限
        Space space;
        Long spaceId = picture.getSpaceId();
        List<String> permissionList = null;
        if (spaceId != null) {
            // 私有空间图片，校验权限，改为使用 Sa-Token 鉴权
            boolean result = StpKit.SPACE.hasPermission(SpaceUserPermissionConstant.PICTURE_VIEW);
            ThrowUtils.throwIf(!result, ErrorCode.NO_AUTH_ERROR);
//            User loginUser = userService.getLoginUser(request);
//            pictureService.checkPictureAuth(loginUser, picture);
            space = spaceService.getById(spaceId);
            ThrowUtils.throwIf(space == null, ErrorCode.NOT_FOUND_ERROR, "空间不存在");
            User loginUser = userService.getLoginUser(request);
            permissionList = spaceUserAuthManager.getPermissionList(space, loginUser);
        }

        PictureVO pictureVO = pictureService.getPictureVO(picture, request);
        pictureVO.setPermissionList(permissionList);
        // 获取封装类
        return ResultUtils.success(pictureVO);
    }

    /**
     * 分页获取图片列表（仅管理员可用）
     */
    @PostMapping("/list/page")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<Picture>> listPictureByPage(@RequestBody PictureQueryRequest pictureQueryRequest) {
        log.info("获取图片信息：{}", pictureQueryRequest);
        long current = pictureQueryRequest.getCurrent();
        long size = pictureQueryRequest.getPageSize();
        // 设置排序参数
        pictureQueryRequest.setSortOrder("createTime");
        // 查询数据库
        Page<Picture> picturePage = pictureService.page(new Page<>(current, size),
                pictureService.getQueryWrapper(pictureQueryRequest));
        return ResultUtils.success(picturePage);
    }

    /**
     * 分页获取图片列表（封装类）
     */
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<PictureVO>> listPictureVOByPage(@RequestBody PictureQueryRequest pictureQueryRequest,
                                                             HttpServletRequest request) {
        long current = pictureQueryRequest.getCurrent();
        long size = pictureQueryRequest.getPageSize();
        // 限制爬虫
//        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        // 空间权限校验
        Long spaceId = pictureQueryRequest.getSpaceId();
        if (spaceId == null) {
            // 普通用户只能查看审核通过的图片
            log.info("查询公共图库图片===========================================================>{}", spaceId);
            pictureQueryRequest.setReviewStatus(PictureReviewStausEnums.PASS.getValue());
            pictureQueryRequest.setNullSpaceId(true);
        } else {
            log.info("查询私有空间图片===========================================================>{}", spaceId);

            // 私有空间，需要校验用户是否有查看该空间的权限，改为使用 Sa-Token 鉴权
            boolean result = StpKit.SPACE.hasPermission(SpaceUserPermissionConstant.PICTURE_VIEW);
            ThrowUtils.throwIf(!result, ErrorCode.NO_AUTH_ERROR);
//            User loginUser = userService.getLoginUser(request);
//            Space space = spaceService.getById(spaceId);
//            ThrowUtils.throwIf(space == null, ErrorCode.PARAMS_ERROR, "空间不存在");
//            if (!loginUser.getId().equals(space.getUserId())) {
//                throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "没有空间访问权限");
//            }
        }

        // 查询数据库
        // 设置排序参数
        pictureQueryRequest.setSortOrder("createTime");
        Page<Picture> picturePage = pictureService.page(new Page<>(current, size),
                pictureService.getQueryWrapper(pictureQueryRequest));
        // 获取封装类
        return ResultUtils.success(pictureService.getPictureVOPage(picturePage, request));
    }

    /**
     * 分页获取图片列表（封装类, 有缓存）
     */
    @Deprecated
    @PostMapping("/list/page/vo/cache")
    public BaseResponse<Page<PictureVO>> listPictureVOByPageWithCache(
            @RequestBody PictureQueryRequest pictureQueryRequest,
            HttpServletRequest request) {
        long current = pictureQueryRequest.getCurrent();
        long size = pictureQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        // 普通用户只能查看审核通过的图片
        pictureQueryRequest.setReviewStatus(PictureReviewStausEnums.PASS.getValue());

        // 1. 构建缓存中的key, 将请求对象转换成json然后再转成md5 用来作为缓存的key
        String pictureQueryRequestJson = JSONUtil.toJsonStr(pictureQueryRequest);
        String hashKey = DigestUtils.md5DigestAsHex(pictureQueryRequestJson.getBytes());
        String cacheKey = String.format("/yunPicture/listPictureVOByPage/%s", hashKey);
        // 2. 查看本地缓存中是否有数据
        String cachedValue = LOCAL_CACHE.getIfPresent(cacheKey);
        if (cachedValue != null) {
            // 缓存命中，返回结果
            log.info("从本地缓存中获取数据");
            Page<PictureVO> cachePage = JSONUtil.toBean(cachedValue, Page.class);
            return ResultUtils.success(cachePage);
        }

        // 3. 如果本地缓存没有数据，查询redis缓存，查看是否有数据
        ValueOperations<String, String> strValueOperations = stringRedisTemplate.opsForValue();
        cachedValue = strValueOperations.get(cacheKey);
        if (cachedValue != null) {
            // 缓存命中，更新本地缓存，返回结果
            log.info("从redis缓存中获取数据");
            LOCAL_CACHE.put(cacheKey, cachedValue);
            Page<PictureVO> cachePage = JSONUtil.toBean(cachedValue, Page.class);
            return ResultUtils.success(cachePage);
        }

        // 4. 如果缓存中没有，就查询数据库
        // 设置排序参数
        pictureQueryRequest.setSortOrder("createTime");
        Page<Picture> picturePage = pictureService.page(new Page<>(current, size),
                pictureService.getQueryWrapper(pictureQueryRequest));
        // 获取封装类
        Page<PictureVO> pictureVOPage = pictureService.getPictureVOPage(picturePage, request);
        // 5. 更新缓存
        // 序列化
        String cacheValue = JSONUtil.toJsonStr(pictureVOPage);
        // 设置redis缓存的过期时间，5-10分钟，随机时间防止缓存雪崩
        int pastTime = 300 + RandomUtil.randomInt(0, 300);
        // 存储到redis缓存中
        log.info("保存到redis缓存中");
        strValueOperations.set(cacheKey, cacheValue, pastTime, TimeUnit.SECONDS);
        // 存储到本地缓存中
        log.info("保存到本地缓存中");
        LOCAL_CACHE.put(cacheKey, cacheValue);
        // 返回查询结果
        return ResultUtils.success(pictureVOPage);
    }

    /**
     * 编辑图片
     *          (可优化，用户可以修改自己的图片，修改后不需要审核)
     */
    @PostMapping("/edit")
    @SaSpaceCheckPermission(value = SpaceUserPermissionConstant.PICTURE_EDIT)
    public BaseResponse<Boolean> editPicture(@RequestBody PictureEditRequest pictureEditRequest, HttpServletRequest request) {
        if (pictureEditRequest == null || pictureEditRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        pictureService.editPicture(pictureEditRequest, request);
        return ResultUtils.success(true);
    }

    /**
     * 获取预制的标签和分类列表
     */
    @GetMapping("/tag_category")
    public BaseResponse<PictureTagCategory> listPictureTagCategory() {
        PictureTagCategory pictureTagCategory = new PictureTagCategory();
        List<String> tagList = Arrays.asList("热门", "搞笑", "生活", "高清", "艺术", "校园", "背景", "简历", "创意");
        List<String> categoryList = Arrays.asList("模板", "电商", "表情包", "素材", "海报");
        pictureTagCategory.setTagList(tagList);
        pictureTagCategory.setCategoryList(categoryList);
        return ResultUtils.success(pictureTagCategory);
    }

    /**
     * 审核图片（仅管理员可用）
     *                      (可优化：可以给用户传递当前图片审核状态，并且允许用户本人查看当前正在审核的图片及其状态)
     */
    @PostMapping("/review")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> doReviewPicture(@RequestBody PictureReviewRequest pictureReviewRequest, HttpServletRequest request) {
        // 参数校验
        log.info("审核图片：{}", pictureReviewRequest);
        ThrowUtils.throwIf(pictureReviewRequest == null, ErrorCode.PARAMS_ERROR);
        // 调用方法
        pictureService.doPictureReview(pictureReviewRequest, request);

        return ResultUtils.success(true);
    }

    /**
     * 批量抓取图片
     *          （可优化，前端执行抓取操作后可以先从后端获取抓取到的图片链接并展示出来，用户确定要保存这些图片后在进行保存到对象存储操作）
     *          （可优化，抓取的图片随机，避免用户输入相同名称时抓取的数据是一样的）
     */
    @PostMapping("/upload/batch")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Integer> uploadPictureByBatch(
            @RequestBody PictureUploadByBatchRequest pictureUploadByBatchRequest,
            HttpServletRequest request) {
        log.info("批量抓取图片：{}", pictureUploadByBatchRequest);
        User loginUser = userService.getLoginUser(request);
        Integer uploadCount = pictureService.uploadPictureByBatch(pictureUploadByBatchRequest, loginUser);
        return ResultUtils.success(uploadCount);
    }

    /**
     * 以图搜图
     */
    @PostMapping("/search/picture")
    public BaseResponse<List<ImageSearchResult>> searchPictureByPicture(@RequestBody SearchPictureByPictureRequest searchPictureByPictureRequest) {
        // 校验参数
        ThrowUtils.throwIf(searchPictureByPictureRequest == null, ErrorCode.PARAMS_ERROR);
        // 获取图片ID
        Long pictureId = searchPictureByPictureRequest.getPictureId();
        ThrowUtils.throwIf(pictureId == null, ErrorCode.PARAMS_ERROR);
        // 获取图片
        Picture picture = pictureService.getById(pictureId);
        ThrowUtils.throwIf(picture == null, ErrorCode.NOT_FOUND_ERROR);
        // 调用以图搜图接口
        List<ImageSearchResult> imageSearchResults = ImageSearchApiFacade.searchImages(picture.getOriginalUrl());

        return ResultUtils.success(imageSearchResults);
    }

    /**
     * 按照颜色搜图
     */
    @PostMapping("/search/color")
    @SaSpaceCheckPermission(value = SpaceUserPermissionConstant.PICTURE_VIEW)
    public BaseResponse<List<PictureVO>> searchPictureByColor(
            @RequestBody SearchPictureByColorRequest searchPictureByColorRequest,
            HttpServletRequest request) {
        // 校验参数
        ThrowUtils.throwIf(searchPictureByColorRequest == null, ErrorCode.PARAMS_ERROR);
        // 获取登录用户
        User loginUser = userService.getLoginUser(request);
        // 调用方法
        List<PictureVO> pictureVOList = pictureService.searchPictureByColor(
                searchPictureByColorRequest.getSpaceId(),
                searchPictureByColorRequest.getPicColor(),
                loginUser);
        // 返回结果
        return ResultUtils.success(pictureVOList);
    }

    /**
     * 批量修改图片信息
     */
    @PostMapping("/edit/batch")
    @SaSpaceCheckPermission(value = SpaceUserPermissionConstant.PICTURE_EDIT)
    public BaseResponse<Boolean> editPictureByBatch(@RequestBody PictureEditByBatchRequest editByBatchRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(editByBatchRequest == null, ErrorCode.PARAMS_ERROR);
        User loginUser = userService.getLoginUser(request);
        pictureService.editPictureByBatch(editByBatchRequest, loginUser);
        return ResultUtils.success(true);
    }

    /**
     * 创建 AI 扩图任务
     */
    @PostMapping("/out_painting/create_task")
    @SaSpaceCheckPermission(value = SpaceUserPermissionConstant.PICTURE_EDIT)
    public BaseResponse<CreateOutPaintingTaskResponse> createPictureOutPaintingTask(
            @RequestBody CreatePictureOutPaintingTaskRequest taskRequest,
            HttpServletRequest request){
        // 校验参数
        ThrowUtils.throwIf(taskRequest == null || taskRequest.getPictureId() == null, ErrorCode.PARAMS_ERROR);
        // 获取用户信息
        User loginUser = userService.getLoginUser(request);
        // 调用接口
        CreateOutPaintingTaskResponse task = pictureService.createPictureOutPaintingTask(taskRequest, loginUser);

        return ResultUtils.success(task);
    }

    /**
     * 获取 AI 扩图任务结果
     */
    @GetMapping("/out_painting/get_taskResult")
    public BaseResponse<GetOutPaintingTaskResponse> getPictureOutPaintingTask(String taskId){
        // 校验参数
        ThrowUtils.throwIf(StrUtil.isBlank(taskId), ErrorCode.PARAMS_ERROR);

        // 调用请求 AI 扩图任务结果接口
        GetOutPaintingTaskResponse taskResult = aliYunAiApi.getOutPaintingTask(taskId);

        return ResultUtils.success(taskResult);
    }

}



